package com.kevin.utility.common;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.kevin.utility.enums.Charset;
import com.kevin.utility.enums.Separator;

public class StringUtil {
    
    public static final String EMPTY = "";
    /**
	 * 通用换行符正则
	 */
	public static final String REGES_NEXT_LINE="[\\n\\r\\n\r\\r\n]";
	
	private static String AND = "and";
	private static String OR = "or";
	private static String WHERE = "where";
	private static String ON = "on";
	private static String GROUP = "group";
	private static String LIMIT = "limit";
	private static String SORT = "sort";
	
    
    /**
     * 是否为空或空串
     * 
     * @param input
     */
    public static boolean isNullOrEmpty(String input){
        return (null == input || EMPTY.equals(input));
    }
    
    /**
     * Null or Empty时，返回默认值。
     * 
     * @param input
     * @param defaultValue
     * @return
     */
    public static String isNullOrEmptyThen(String input, String defaultValue){
        return (isNullOrEmpty(input)) ? defaultValue : input;
    }
    
    /**
     * 若为空时返回一个设定值
     * 
     * @param input
     * @param defaultValue
     * @return
     */
    public static String isNullThen(Object input, String defaultValue){
        return (null == input) ? defaultValue : input.toString();
    }
    public static String isNullThen(Object input){
        return isNullThen(input, EMPTY);
    }
    
    /**
     * 返回字符串trim值
     * 若为null返回空串
     * 
     * @param input
     * @return
     */
    public static String trimToEmpty(String input){
        if (isNullOrEmpty(input)){
            return EMPTY;
        }
        return input.trim();
    }
    
    /**
     * 截取长度
     * 默认使用GB2312
     * 
     * @param str
     * @param subSLength
     * @param charset
     * @return
     */
    public static String subString(String str, int subSLength, Charset charset) {
        try{
           if (str == null)    
               return "";
           else{
               if (null == charset){
                   charset = Charset.GB2312;
               }
               int tempSubLength = subSLength;//截取字节数  
               String subStr = str.substring(0, str.length()<subSLength ? str.length() : subSLength);//截取的子串    
               int subStrByetsL = subStr.getBytes(charset.toString()).length;//截取子串的字节长度
               // 说明截取的字符串中包含有汉字    
               while (subStrByetsL > tempSubLength){    
                   int subSLengthTemp = --subSLength;  
                   subStr = str.substring(0, subSLengthTemp>str.length() ? str.length() : subSLengthTemp);    
                   subStrByetsL = subStr.getBytes(charset.toString()).length;  
                   //subStrByetsL = subStr.getBytes().length;  
               }    
               return subStr;   
           }  
        } catch (Exception ex){
            return "";
        }
    }
    /**
     * 截取长度
     * 默认使用GB2312
     * 
     * @param str
     * @param subSlength
     * @return
     */
    public static String subString(String str, int subSlength){
        return subString(str, subSlength, Charset.GB2312);
    }
    
    /**
     * 替换字符串%s
     * @param str
     * @param replace
     * @return
     */
    public static String getString(String str, String replace){
    	return String.format(str, replace);
    }
    
    /**
     * 动态批量替换SQL中的条件字符串范式
     * @param sql
     * @param id
     * @param value
     * @return
     */
    public static String processSql(String sql, String id, String value ){
		List<String> queue = new LinkedList<String>();
		int beginIndex = -1;
		if(StringUtils.isNotBlank(value)){
			while(sql.indexOf(id) > -1){
				sql = sql.replace(id, value);
			}
			return sql;
		}
		int  position = sql.indexOf(id)-1;
		beginIndex = position+1;
		if(position < 0){
			return sql;
		}
		StringBuilder sb = new StringBuilder();
		for(int i= position; i>0;i--){
			char tmp = sql.charAt(i);
			if(!(Character.isLetter(tmp) || Character.isDigit(tmp))){
				if(ON.equals(sb.toString().toLowerCase())){
					queue.add(sb.toString().trim());
					break;
				}else if(WHERE.equals(sb.toString().toLowerCase())){
					queue.add(sb.toString().trim());
					break;
				}else if(AND.equals(sb.toString().toLowerCase())){
					queue.add(sb.toString().trim());
					break;
				}else if(OR.equals(sb.toString().toLowerCase())){
					queue.add(sb.toString().trim());
					beginIndex = i;
					break;
				}
				if(sb.length() > 0){
					beginIndex = i;
					sb.delete(0,sb.length());
				}
			}else if(tmp == '(' ){
				queue.add(tmp+"");
			}else{
				sb.insert(0, tmp);
			}
		}
		sb.delete(0,sb.length());
		int endIndex = sql.length();
		for(int i= position+id.length()+1; i<sql.length();i++){
			char tmp = sql.charAt(i);
			if(!(Character.isLetter(tmp) || Character.isDigit(tmp))){
				if(WHERE.equals(sb.toString().toLowerCase())){
					return sql.replace(sql.substring(beginIndex, endIndex), " 1=1 ");
				}else if(AND.equals(sb.toString().toLowerCase())){
					return sql.replace(sql.substring(beginIndex, endIndex), " 1=1 ");
				}else if(OR.equals(sb.toString().toLowerCase())&&queue.size() >0&&queue.get(0).equals(OR)){
					return sql.replace(sql.substring(beginIndex, endIndex), "");
				}else if(OR.equals(sb.toString().toLowerCase())){
					return sql.replace(sql.substring(beginIndex, i), "");
				}else if(GROUP.equals(sb.toString().toLowerCase())){
					return sql.replace(sql.substring(beginIndex, endIndex), " 1=1 ");
				}else if(LIMIT.equals(sb.toString().toLowerCase())){
					return sql.replace(sql.substring(beginIndex, endIndex), " 1=1 ");
				}else if(SORT.equals(sb.toString().toLowerCase())){
					return sql.replace(sql.substring(beginIndex, endIndex), " 1=1 ");
				}
				endIndex = i;
				sb.delete(0,sb.length());
				continue;
			}else if(tmp == ')' ){
				sb.delete(0,sb.length());
				while (true){
					if(queue.size() == 0){
						break;
					}
					String content = queue.remove(0);
					if(content.equals("(")){
						break;	
					}else if(content.equals(OR)){
						return sql.replace(sql.substring(beginIndex, i), "");
					}
				}
				endIndex = i;
			}else{
				sb.append(tmp);
			}
		}
		return sql.replace(sql.substring(beginIndex, sql.length()), " 1=1 ");
	}
    
    public static boolean tryParseInt(String value) {
    	if (isNullOrEmpty(value)) {
    		return false;
    	}
    	try {
    		Integer.parseInt(value);
    		return true;
    	} catch (Exception ex) {
    		return false;
    	}
    }
    
    @SuppressWarnings({ "rawtypes" })
	public static String concat(List list, Separator separator) {
    	if (!CollectionUtil.hasValue(list)) {
    		return EMPTY;
    	}
    	String result = EMPTY;
    	String sep = EMPTY;
    	
    	if (null != separator) {
    		sep = separator.getText();
    	}
    	for (Object o : list) {
    		if (!isNullOrEmpty(isNullThen(o))) {
	    		if (!isNullOrEmpty(result)) {
	    			result += sep;
	    			result += isNullThen(o);
	    		}
    		}
    	}
    	return result;
    }
}
